package org.makcro.sms.services.chat.base.filters;

import org.apache.log4j.Logger;
import org.makcro.sms.services.chat.base.dao.AnswerDao;
import org.makcro.sms.services.chat.base.service.ResponseReport;
import org.makcro.sms.services.chat.base.service.SMSChatServiceImpl;
import org.makcro.sms.services.chat.model.Answer;

import com.klikmee.sms.core.commons.filters.ProcessItemFilter;

/**
 * Filter designed to process charged response reports.
 * 
 * @author makcro
 * 
 */
public class ChargedMessageResponseReportFilterImpl implements ProcessItemFilter<ResponseReport> {

	// Logger instance
	private Logger		logger	= Logger.getLogger( ChargedMessageResponseReportFilterImpl.class );

	// dao used to access answers
	private AnswerDao	answerDAO;

	@Override
	public boolean process(ResponseReport item) {
		String status = item.getStatus();
		Long coreId = item.getCoreId();

		// find answer by responseId
		Answer answer = answerDAO.findByResponseId( coreId );

		if (answer != null) {
			// resolve status
			if (status.equals( SMSChatServiceImpl.ANSWER_DELIVERED )) {
				answer.setAnswerDelivered( true );
			}
			else if (status.equals( SMSChatServiceImpl.ANSWER_NOT_DELIVERED )) {
				answer.setAnswerDelivered( false );
			}
			this.answerDAO.edit( answer );
			logger.debug( String.format( "Processed status report for message coreId = [%s] with status [%s]", coreId, status ) );
			return true;
		}
		else {
			logger.warn( String.format( "Received status report for unknowen answer, coreId = [%s]", coreId ) );
			return false;
		}
	}
	
	public void setAnswerDAO(AnswerDao answerDAO) {
		this.answerDAO = answerDAO;
	}

}
